<template>
  <div class="player" v-show="playlist.length>0">
    <transition
      name="normal"
      @enter="enter"
      @after-enter="afterEnter"
      @leave="leave"
      @after-leave="afterLeave"
    >
      <div class="normal-player" v-show="fullScreen">
        <div class="background">
          <img width="100%" height="100%" :src="currentSong.image" />
        </div>
        <div class="top">
          <div class="back" @click="goBack">
            <i class="iconfont icon--dropdown"></i>
          </div>
          <h1 class="title" v-html="currentSong.name"></h1>
          <h2 class="subtitle" v-html="currentSong.singer"></h2>
        </div>
        <div
          class="middle"
          @touchstart="middleTouchStart"
          @touchmove="middleTouchMove"
          @touchend="middleTouchEnd"
        >
          <div class="middle-l" ref="middleL">
            <div class="cd-wrapper" ref="cdWrapper">
              <div class="cd" :class="cdCls">
                <img class="image" :src="currentSong.image" />
              </div>
            </div>
            <div class="playing-lyric-wrapper">
              <div class="playing-lyric">{{playingLyric}}</div>
            </div>
          </div>
          <scroll class="middle-r" ref="lyricList" :data="currentLyric && currentLyric.lines">
            <div class="lyric-wrapper">
              <div v-if="currentLyric">
                <p
                  ref="lyricLine"
                  class="text"
                  :class="{'current' : currentlineNum == index}"
                  v-for="(line,index) in currentLyric.lines"
                  :key="index"
                >{{line.txt}}</p>
              </div>
            </div>
          </scroll>
          <!-- <p v-show="!currentLyric" class="noLyric">当前歌曲为纯音乐，请欣赏</p> -->
        </div>
        <div class="bottom">
          <div class="dot-wrapper">
            <span class="dot" :class="{'active':currentShow === 'cd'}"></span>
            <span class="dot" :class="{'active':currentShow === 'lyric'}"></span>
          </div>
          <div class="progress-wrapper">
            <!-- 当期的播放时间 -->
            <span class="time time-l">{{format(currentTime)}}</span>
            <div class="progress-bar-wrapper">
              <progress-bar :precent="precent" @precentChange="onProgressBarChange"></progress-bar>
            </div>
            <!-- 音乐的总时长 -->
            <span class="time time-r">{{format(currentSong.duration)}}</span>
          </div>
          <div class="operators">
            <div class="icon i-left" @click="changeMode">
              <i :class="modeIcon" class="iconfont"></i>
            </div>
            <div class="icon i-left" @click.stop="prev" :class="disableCls">
              <i class="iconfont icon-pre_song"></i>
            </div>
            <div class="icon i-center" @click.stop="togglePlay" :class="disableCls">
              <i :class="playIcon"></i>
            </div>
            <div class="icon i-right" @click.stop="next" :class="disableCls">
              <i class="iconfont icon-next_song"></i>
            </div>
            <div class="icon i-right" @click.stop="toggleFavorite(currentSong)">
              <i  :class="favoriteIcon(currentSong)"></i>
            </div>
          </div>
        </div>
      </div>
    </transition>
    <Play-list ref="PlayList"></Play-list>
    <transition name="mini">
      <div class="mini-player" v-show="!fullScreen" @click="toFullShow">
        <div class="icon">
          <img :class="cdCls" width="40" height="40" :src="currentSong.image" />
        </div>
        <div class="text">
          <h2 class="name" v-html="currentSong.name"></h2>
          <p class="desc" v-html="currentSong.singer"></p>
        </div>
        <div class="control">
          <progress-circle :radius="radius" :precent="precent">
            <i @click.stop="togglePlay" class="iconfont icon-mini" :class="minIcon"></i>
          </progress-circle>
        </div>
        <div class="control" @click.stop="showPlayList">
          <i class="iconfont icon-music"></i>
        </div>
      </div>
    </transition>

    <audio
      ref="audio"
      :src="currentSong.url"
      @canplay="ready"
      @error="error"
      @timeupdate="updateTime"
      @ended="end"
    ></audio>
  </div>
</template>
<script>
import { mapMutations, mapGetters, mapActions } from "vuex";
import animations from "create-keyframe-animation";
import progressBar from "@/base/progress-bar/progress-bar";
import progressCircle from "@/base/progress-circle/progress-circle";
import { playMode } from "@/common/js/config";
import { shuffle } from "@/common/js/util";
import Lyric from "lyric-parser";
import scroll from "@/base/scroll/scroll";
import PlayList from "../playlist/playlist";
import { playerMixin } from "@/common/js/mixin";
let audio = {};
export default {
  mixins: [playerMixin],
  data() {
    return {
      songReady: false, //标记歌曲是否已经缓冲准备好
      currentTime: 0, //当前歌曲的播放时间
      radius: 32,
      currentLyric: null, //当前播放的歌词
      currentlineNum: 0, //当前歌词所在的行，方便后面制作高亮显示
      currentShow: "cd", //当前展示的是cd还是歌词
      playingLyric: "", //展示当前播放的是哪一句歌词
      type: 0 ,//标志是从哪个页面进来的，1表示是推荐首页进来的
    };
  },
  components: {
    progressBar,
    progressCircle,
    scroll,
    PlayList
  },
  computed: {
    ...mapGetters(["fullScreen", "currentSong",'playlist']),
    //计算播放按钮的类样式
    playIcon() {
      return this.playing
        ? "iconfont icon-music_playing"
        : "iconfont icon-play";
    },
    //计算小的播放按钮
    minIcon() {
      return this.playing ? "icon-mini_pause" : "icon-min_play";
    },
    // 计算cd旋转暂停的播放样式
    cdCls() {
      return this.playing ? "play" : "play  pause";
    },
    //当歌曲没有准备好的时候，将按钮置灰状态
    disableCls() {
      return this.songReady ? "" : "disable";
    },
    //计算播放的进度条的进度比例
    precent() {
      return this.currentTime / this.currentSong.duration;
    }

  },
  created() {
    this.touch = {};
    let type = this.$route.query.type;
  },
  mounted() {},
  methods: {
    // 判断歌曲是否有播放链接
    checkSongUrl(item) {
      // this.playlist.
    },
    //点击大的收起播放器
    goBack() {
      this.changeFeull(false);
    },
    //点击放大播放器
    toFullShow() {
      this.changeFeull(true);
    },
    // create-keyframe的动画
    _getPosandScale() {
      const targetWidth = 40;
      const paddingLeft = 40;
      const paddingBottom = 30;
      const paddingTop = 80;
      const width = window.innerWidth * 0.8;
      const scale = targetWidth / width;
      const x = -(window.innerWidth / 2 - paddingLeft);
      const y = window.innerHeight - paddingTop - width / 2 - paddingBottom;
      return {
        x,
        y,
        scale
      };
    },
    //动画的钩子函数
    enter(el, done) {
      //el是dom,done是回调函数
      const { x, y, scale } = this._getPosandScale();

      let animation = {
        0: {
          transform: `translate3d(${x}px,${y}px,0) scale(${scale})`
        },
        60: {
          transform: `translate3d(0,0,0) scale(1.1)`
        },
        100: {
          transform: `translate3d(0,0,0) scale(1)`
        }
      };

      animations.registerAnimation({
        name: "move",
        animation,
        presets: {
          duration: 400,
          easing: "linear"
        }
      });

      animations.runAnimation(this.$refs.cdWrapper, "move", done);
    },
    afterEnter() {
      //清空animation
      animations.unregisterAnimation("move");
      this.$refs.cdWrapper.style.animation = "";
    },
    leave(el, done) {
      this.$refs.cdWrapper.style.transition = "all 0.4s";
      const { x, y, scale } = this._getPosandScale();
      this.$refs.cdWrapper.style[
        `transform`
      ] = `translate3d(${x}px,${y}px,0) scale(${scale})`;
      this.$refs.cdWrapper.addEventListener("transitionend", done);
    },
    afterLeave() {
      this.$refs.cdWrapper.style.transition = "";
      this.$refs.cdWrapper.style[`transform`] = "";
    }, //动画结束
    //点击播放控制按钮，操作歌曲的关闭和播放
    togglePlay() {
      //如果歌曲没有准备好，不让他点
      if (!this.songReady) {
        return;
      }
      this.changePlaying(!this.playing);
      // 解决点击暂停后歌词仍然滚动的原因
      if (this.currentLyric) {
        this.currentLyric.togglePlay();
      }
    },
    //点击上一首
    prev() {
      //如果歌曲没有准备好，不让他点
      if (!this.songReady) {
        return;
      }
      // 处理边界情况，和next的情况一样
      if (this.playlist.length === 1) {
        this.loop();
      } else {
        let currentIndex = this.currentIndex - 1;
        if (currentIndex === -1) {
          currentIndex = this.playlist.length - 1;
        }
        this.set_current_index(currentIndex);
        if (!this.playing) {
          this.togglePlay();
        }
      }
      this.songReady = false;
    },
    //点击下一首
    next() {
      //如果歌曲没有准备好，不让他点
      if (!this.songReady) {
        return;
      }
      // 处理边界情况，歌曲的列表里面只有一首歌，
      // 这样index就不会变，后面检测到id不变，在监听currentSong的时候，
      // 那么就不会改变当前的播放歌曲，进度之类的就会有问题，需要解决
      if (this.playlist.length === 1) {
        this.loop(); //这就是一个单曲循环的效果
        return;
      } else {
        let currentIndex = this.currentIndex + 1;
        if (currentIndex === this.playlist.length) {
          currentIndex = 0;
        }
        this.set_current_index(currentIndex);
        let audio = this.$refs.audio;
        audio.play();
        if (!this.playing) {
          this.togglePlay();
        }
      }
      this.songReady = false;
    },
    //查看audio中歌曲是否准备好
    ready() {
      this.songReady = true;
      this.savePlayHistory(this.currentSong);
    },
    //当歌曲加载失败都会触发这个函数（例如歌曲不存在）
    error() {
      this.songReady = false;
    },
    //audio播放，会派发的事件，这个回调函数
    updateTime(e) {
      this.currentTime = e.target.currentTime;
    },
    //当歌曲播放完，会派发这个事件
    end() {
      // 如果当前的播放模式是单曲循环，播放完之后，还是循环播放这首歌，否则就是播放下一首
      if (this.mode === playMode.loop) {
        this.loop();
      } else {
        this.next();
      }
    },
    //循环播放当前的歌曲
    loop() {
      // 把audio的播放时间改为0
      this.$refs.audio.currentTime = 0;
      this.$refs.audio.play();
      //解决单曲循环的时候，播放完跳转到播放结束再次播放，歌词位置不对的原因
      if (this.currentLyric) {
        this.currentLyric.seek(0);
      }
    },
    //将时间戳转换成时分秒
    format(interval) {
      interval = interval | 0; //向下取整
      const minute = (interval / 60) | 0;
      const seconed = this._pad(interval % 60);
      return `${minute}:${seconed}`;
    },
    // 控制时间，补零的操作
    _pad(num, n = 2) {
      //n代表最后这个字符串的长度
      let len = num.toString().length;
      while (len < n) {
        num = "0" + num;
        len++;
      }
      return num;
    },
    //计算进度条拖动后，当前要显示的播放的时长
    onProgressBarChange(precent) {
      const currentTime = this.currentSong.duration * precent; //总时长*拖动的比例=将要播放的时长
      this.$refs.audio.currentTime = currentTime;
      if (!this.playing) {
        this.togglePlay();
      }
      //解决拖动进度条时，歌词不改变的原因
      if (this.currentLyric) {
        this.currentLyric.seek(currentTime * 1000);
      }
    },
    //处理歌词的函数,逻辑
    getLyric(type) {
      this.currentSong
        .getMusic_Lyric(type)
        .then(lyric => {
          this.currentLyric = new Lyric(lyric, this.handleLyric); //这个this.handleLyric回调函数，当每行歌词发生变化就回调一次
          if (this.playing) {
            this.currentLyric.play();
          }
        })
        .catch(() => {
          //当获取不到歌词的时候的异常操作，异常的捕获
          //一些清理的操作
          this.currentLyric = null;
          this.playingLyric = "123456";
          this.currentlineNum = 0;
        });
    },
    //歌词的回调函数
    handleLyric({ lineNum, txt }) {
      this.currentlineNum = lineNum;
      if (lineNum > 5) {
        //保证当前的歌词始终在屏幕的中间，自家会滚动到中间
        let lineEl = this.$refs.lyricLine[lineNum - 5];
        this.$refs.lyricList.scrollToElement(lineEl, 1000);
      } else {
        this.$refs.lyricList.scrollTo(0, 0, 1000);
      }
      //在cd区域展示当前播放的歌词
      this.playingLyric = txt;
    },
    //中间歌词区域的滑动模块的滑动
    middleTouchStart(e) {
      this.touch.initiated = true;
      const touch = e.touches[0];
      this.touch.startX = touch.pageX;
      this.touch.startY = touch.pageY;
    },
    middleTouchMove(e) {
      if (!this.touch.initiated) {
        return;
      }
      const touch = e.touches[0];
      const deltaX = touch.pageX - this.touch.startX;
      const deltaY = touch.pageY - this.touch.startY;
      if (Math.abs(deltaY) > Math.abs(deltaX)) {
        //当时纵向滚动的时候，禁止，只允许横向滚动
        return;
      }
      const left = this.currentShow === "cd" ? 0 : -window.innerWidth;
      const offsetWidth = Math.min(
        0,
        Math.max(-window.innerWidth, left + deltaX)
      );
      this.touch.percent = Math.abs(offsetWidth / window.innerWidth);
      //左滑deltaX是负数，width就会是-window.innerWidth
      this.$refs.lyricList.$el.style[
        "transform"
      ] = `translate3d(${offsetWidth}px,0,0)`;
      this.$refs.lyricList.$el.style["transitionDuration"] = 0;
      this.$refs.middleL.style["opacity"] = 1 - this.touch.percent;
      this.$refs.middleL.style["transitionDuration"] = 0;
    },
    middleTouchEnd() {
      let offsetWidth;
      let opacity;
      if (this.currentShow === "cd") {
        //像左滑
        if (this.touch.percent > 0.1) {
          offsetWidth = -window.innerWidth; //最终停的位置
          opacity = 0;
          this.currentShow = "lyric";
        } else {
          offsetWidth = 0;
          this.currentShow = "cd";
          opacity = 1;
        }
      } else {
        //像右滑
        if (this.touch.percent < 0.9) {
          offsetWidth = 0;
          this.currentShow === "cd";
          opacity = 1;
        } else {
          offsetWidth = -window.innerWidth; //最终停的位置
          opacity = 0;
        }
      }
      this.$refs.lyricList.$el.style[
        "transform"
      ] = `translate3d(${offsetWidth}px,0,0)`;
      const time = 300;
      this.$refs.lyricList.$el.style["transitionDuration"] = `${time}ms`;
      this.$refs.middleL.style["opacity"] = opacity;
      this.$refs.middleL.style["transitionDuration"] = 0;
    },
    // 展示播放列表
    showPlayList() {
      this.$refs.PlayList.show();
    },
    ...mapMutations({
      changeFeull: "SET_FULL_STATE"
    }),
    ...mapActions(["savePlayHistory"])
  },
  watch: {
    currentSong(newSong, oldSong) {
      if (!newSong.id) {
        return;
      }
      if (newSong.id === oldSong.id) {
        return;
      }
      if (this.currentLyric) {
        //这个时候有歌词，就清除，防止切换歌曲的时候歌曲来回切调
        this.currentLyric.stop();
      }
      // 为了解决微信中，从后台切换到前台的时候的问题(js不执行，songReady不能改变从true)
      // ，改用setTimeout,
      // 不用this.$nextTick

      setTimeout(() => {
        if (this.currentSong.url != "") {
          this.$refs.audio.play();
          this.getLyric();
        } else {
          this.$refs.audio.pause();
          this.changePlaying(false);
        }
      }, 1000);
    },
    playing(newPlay) {
      audio = this.$refs.audio;
      this.$nextTick(() => {
        newPlay ? audio.play() : audio.pause();
      });
    },
    favoriteList(){

    }
  }
};
</script>
<style lang="stylus" scoped>
@import '../../common/stylus/variable.styl';
@import '../../common/stylus/mixin.styl';

.player {
  .normal-player {
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    z-index: 150;
    background: $color-background;

    .background {
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      z-index: -1;
      opacity: 0.6;
      filter: blur(20px);
    }

    .top {
      position: relative;
      margin-bottom: 25px;

      .back {
        position: absolute;
        top: 8px;
        left: 8px;
        z-index: 50;
        color: $color-theme;

        .icon-back {
          display: block;
          padding: 9px;
          font-size: $font-size-large-x;
          color: $color-theme;
          transform: rotate(-90deg);
        }
      }

      .title {
        width: 70%;
        margin: 0 auto;
        line-height: 40px;
        text-align: center;
        no-wrap();
        font-size: $font-size-large;
        color: $color-text;
      }

      .subtitle {
        line-height: 20px;
        text-align: center;
        font-size: $font-size-medium;
        color: $color-text;
      }
    }

    .middle {
      position: fixed;
      width: 100%;
      top: 80px;
      bottom: 170px;
      white-space: nowrap;
      font-size: 0;

      .middle-l {
        display: inline-block;
        vertical-align: top;
        position: relative;
        width: 100%;
        height: 0;
        padding-top: 80%;

        .cd-wrapper {
          position: absolute;
          left: 10%;
          top: 0;
          width: 80%;
          height: 100%;

          .cd {
            width: 100%;
            height: 100%;
            box-sizing: border-box;
            border: 10px solid rgba(255, 255, 255, 0.1);
            border-radius: 50%;

            &.play {
              animation: rotate 20s linear infinite;
            }

            &.pause {
              animation-play-state: paused;
            }

            .image {
              position: absolute;
              left: 0;
              top: 0;
              width: 100%;
              height: 100%;
              border-radius: 50%;
            }
          }
        }

        .playing-lyric-wrapper {
          width: 80%;
          margin: 30px auto 0 auto;
          overflow: hidden;
          text-align: center;

          .playing-lyric {
            height: 20px;
            line-height: 20px;
            font-size: $font-size-medium;
            color: $color-text-l;
          }
        }
      }
       .noLyric{
            color: #fff;
            font-size: 15px;
            position: fixed;
            top: 50%;
            left: 50%;
            transform :translate(-50%)
          }

      .middle-r {
        display: inline-block;
        vertical-align: top;
        width: 100%;
        height: 100%;
        overflow: hidden;
       
        .lyric-wrapper {
          width: 80%;
          margin: 0 auto;
          overflow: hidden;
          text-align: center;

          .text {
            line-height: 32px;
            color: $color-text-l;
            font-size: $font-size-medium;

            &.current {
              color: $color-text;
            }
          }
          
        }
      }
    }

    .bottom {
      position: absolute;
      bottom: 50px;
      width: 100%;

      .dot-wrapper {
        text-align: center;
        font-size: 0;

        .dot {
          display: inline-block;
          vertical-align: middle;
          margin: 0 4px;
          width: 8px;
          height: 8px;
          border-radius: 50%;
          background: $color-text-l;

          &.active {
            width: 20px;
            border-radius: 5px;
            background: $color-text-ll;
          }
        }
      }

      .progress-wrapper {
        display: flex;
        align-items: center;
        width: 80%;
        margin: 0px auto;
        padding: 10px 0;

        .time {
          color: $color-text;
          font-size: $font-size-small;
          flex: 0 0 30px;
          line-height: 30px;
          width: 30px;

          &.time-l {
            text-align: left;
          }

          &.time-r {
            text-align: right;
          }
        }

        .progress-bar-wrapper {
          flex: 1;
        }
      }

      .operators {
        display: flex;
        align-items: center;

        .icon {
          flex: 1;
          color: $color-theme;

          &.disable {
            color: $color-theme-d;
          }

          i {
            font-size: 30px;
          }
        }

        .i-left {
          text-align: right;
        }

        .i-center {
          padding: 0 20px;
          text-align: center;

          i {
            font-size: 40px;
          }
        }

        .i-right {
          text-align: left;
        }

        .icon-favorite {
          color: $color-sub-theme;
        }
      }
    }

    &.normal-enter-active, &.normal-leave-active {
      transition: all 0.4s;

      .top, .bottom {
        transition: all 0.4s cubic-bezier(0.86, 0.18, 0.82, 1.32);
      }
    }

    &.normal-enter, &.normal-leave-to {
      opacity: 0;

      .top {
        transform: translate3d(0, -100px, 0);
      }

      .bottom {
        transform: translate3d(0, 100px, 0);
      }
    }
  }

  .mini-player {
    display: flex;
    align-items: center;
    position: fixed;
    left: 0;
    bottom: 0;
    z-index: 180;
    width: 100%;
    height: 60px;
    background: $color-highlight-background;

    &.mini-enter-active, &.mini-leave-active {
      transition: all 0.4s;
    }

    &.mini-enter, &.mini-leave-to {
      opacity: 0;
    }

    .icon {
      flex: 0 0 40px;
      // width: 40px;
      padding: 0 10px 0 20px;

      img {
        border-radius: 50%;

        &.play {
          animation: rotate 10s linear infinite;
        }

        &.pause {
          animation-play-state: paused;
        }
      }
    }

    .text {
      display: flex;
      flex-direction: column;
      justify-content: center;
      flex: 1;
      line-height: 20px;
      overflow: hidden;

      .name {
        margin-bottom: 2px;
        no-wrap();
        font-size: $font-size-medium;
        color: $color-text;
      }

      .desc {
        no-wrap();
        font-size: $font-size-small;
        color: $color-text-d;
      }
    }

    .control {
      flex: 0 0 30px;
      // width: 30px;
      padding: 0 10px;
      color: $color-theme;

      .icon-mini_pause, .icon-min_play, .icon-music {
        font-size: 22px;
        color: $color-theme;
      }

      .icon-mini {
        font-size: 20px;
        position: absolute;
        left: 7px;
        top: 6px;
      }
    }
  }
}

@keyframes rotate {
  0% {
    transform: rotate(0);
  }

  100% {
    transform: rotate(360deg);
  }
}
</style>
